package common

import (
	"errors"
	"io"
	"math/rand"
	"mime/multipart"
	"os"
	"strconv"
	"strings"
)

func UploadVideo(video *multipart.FileHeader, file multipart.File) (string, error) {
	//todo 判断视频文件大小
	if video.Size > 1024*1024*10 {
		return "", errors.New("视频过大")
	}
	str := NameRom()
	//todo 判断文件格式
	videoSub := []string{"mp4", "mov"}
	videoName := str + "." + strings.Split(video.Filename, ".")[1]
	if !strings.Contains(strings.Join(videoSub, ","), strings.Split(video.Filename, ".")[1]) {
		return "", errors.New("格式有误")
	}
	//todo 创建文件夹
	_, err := os.Stat("./2109a/video/")
	if err != nil {
		os.MkdirAll("./2109a/video/", os.ModeCharDevice)
	}
	//todo 视频保存本地
	openVideo, err := os.OpenFile("./2109a/video/"+videoName, os.O_CREATE|os.O_WRONLY|os.O_APPEND, 0777)
	if err != nil {
		return "", err
	}
	_, err = io.Copy(openVideo, file)
	if err != nil {
		return "", err
	}
	return "./2109a/video/" + videoName, nil
}
func UploadImg(img *multipart.FileHeader, file multipart.File) (string, error) {
	//todo 判断视频文件大小
	if img.Size > 1024*1024*3 {
		return "", errors.New("格式有误")
	}
	//todo 判断文件格式
	str := NameRom()
	imgSub := []string{"gif", "png", "jpg", "jpeg", "GIF", "PNG", "JPG", "JPEG"}
	imgName := str + "." + strings.Split(img.Filename, ".")[1]
	if !strings.Contains(strings.Join(imgSub, ","), strings.Split(img.Filename, ".")[1]) {
		return "", errors.New("格式有误")
	}
	//todo 创建文件夹
	_, err := os.Stat("./2109a/img/")
	if err != nil {
		os.MkdirAll("./2109a/img/", os.ModeCharDevice)
	}
	//todo 图片保存本地
	open, err := os.OpenFile("./2109a/img/"+imgName, os.O_CREATE|os.O_WRONLY|os.O_APPEND, 0777)
	if err != nil {
		return "", err
	}
	_, err = io.Copy(open, file)
	if err != nil {
		return "", err
	}
	return imgName, nil
}
func NameRom() string {
	max := 9999
	min := 1000
	num := rand.Intn((max - min - 1) + min)
	return strconv.Itoa(num)
}
